var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var page = 1;
var wxAuthFail = true; 

var inviteuid = '';

Page({  
  data: {  
    uid: 0,
    tc: 0,
    token: '',
    userinfo:{},

    user_jifen: 0,
    colorSet: '',

    hasShare: false,

    circleList: [],//圆点数组  
    awardList: [],//奖品数组  
    colorCircleFirst: '#FFDF2F',//圆点颜色1  
    colorCircleSecond: '#FE4D32',//圆点颜色2  
    colorAwardDefault: '#F5F0FC',//奖品默认颜色  
    colorAwardSelect: '#FE4D32',//奖品选中颜色  
    indexSelect: 0,//被选中的奖品index  
    resData: [],
    isRunning: false,//是否正在抽奖  
    imageAward: [],//奖品图片数组  
    nameAward:[],//奖品名字数组
    idAward: [],
    kucunAward:[],//奖品库存数组
    goodsList: [],
    gwc_count: 0,
    guigeData: [],
    selectGuige: '',
    countValue: 1,
    inviteCount:0,
    goodsinfoArr:[],
    openid: '',

    cardlist:[], //卡券列表
    gameIntegral:10, //抽奖所需积分
    gametu:[], //广告图
  },  
   
  onLoad: function (data) {  
    // inviteuid = '';
    
    //是否是从 别人分享的 页面点进来的
    inviteuid = data.inviteuid ? data.inviteuid : '';
    this.getLoginInfo();
    this.loadInviteCount();
    var that = this;
    var tc = app.get_tc();//简体繁体转换
    that.setData({
      tc: tc
    })
    var titlename = tc == 1 ? '積分抽獎' : '积分抽奖';
    wx.setNavigationBarTitle({
      title: titlename,
    }); 
 

    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color
      })
      that.resetNavColor();
    });

    

    topicid = data.topicid || "";

    var pages = getCurrentPages();
    var curPageIndex = pages.length;
    //如果是分享进来 或者 当前栈下标 是 1 都认为是分享进来的  因为分享人可能没授权登录 无法分享邀请码
    var isShare = (inviteuid || curPageIndex <= 1);
    this.setData({
      hasShare: isShare,
      topicid: topicid,
      isOnLoad: true
    })


    //获取绑定orgid信息
    app.GetUserInfo(util.orgid, function (res) {
      console.log("绑定机构信息：", res);
      wx.setNavigationBarTitle({
        title: res.uname,
      });
      that.setData({
        org_name: res.uname
      })
    });


    
  },  

  getLoginInfo: function(){
    var that = this;
    app.LoginUserInfo(function (res) {
      console.log("mine login:", res);
      wxAuthFail = res == -1;//用户拒绝授权
      if (wxAuthFail) {
        return;
      }
      that.setData({
        uid: res.uid,
        openid: res.wxsmall_openid,
        token: res.token
      });
      that.getJifen();

      util.api({
        data: {
          "uid": res.uid,
          "publickey": util.publiccode,
          "ac": "userinfo"
        },
        success: function (responseData) {
          console.log(responseData.data);
          that.setData({
            userinfo: responseData.data
          });
        }
      });

      //获取抽奖所需积分
        util.api({
          data: {
            "uid": res.uid,
            "orgid":util.orgid,
            "publickey": util.publiccode,
            "ac": "getGameIntegral"
          },
          success: function (responseData) {
            console.log("gameIntegral:",responseData.data);
            var resutl = responseData.data;
    
            if(resutl.res != false){
              that.setData({
                gameIntegral: responseData.data[0].gameIntegral
              });
            }
            
          }
        });
   
    }, inviteuid);
  },

  onShow: function () {
    // 页面显示
    // this.getShangpin();
    this.getcardlist();
    this.getGametu();
  },

  //获取广告图
  getGametu:function(){
     var that = this;
    util.api({
      data: {
        "uid": that.data.uid,
        "orgid":util.orgid,
        "publickey": util.publiccode,
        "ac": "getGametu"
      },
  
      success: function (responseData) {
        console.log("获取广告图",responseData.data);
        that.setData({
          gametu:responseData.data
        })
      }
    });
  },

  //获取商品列表
  getShangpin:function(){
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "topiclist",
      topictype: '4',
      toporder: '1',
      tc: '1',
      orgid: util.orgid,
      gtype: '189190',
      gtype: '252',
      zhiding: '',
      page: 1,
      num: 8,
      sellprice:0,
      hot:0
    };
     console.log("商品参数：", params);
    util.api({
      data: params,
      success: function (responseData) {
     
        console.log("商店商品数据:", responseData);
        var resData = responseData.data;
        var imageAward = [];
        var nameAward = [];
        var kucunAward = [];
        var idAward = [];
        for(var i = 0; i<resData.length; i++){
          imageAward[i] = resData[i].photos.split(",")[0];
          nameAward[i] = resData[i].topictitle;
          kucunAward[i] = resData[i].kucun;
          idAward[i] = resData[i].id;
        }
        console.log("商店商品图片:", imageAward);
        console.log("商店商品名字:", nameAward);
        console.log("商店商品库存:", kucunAward);
        console.log("商店商品id:", idAward);
        that.setData({
          resData:resData,
          imageAward: imageAward,
          nameAward:nameAward,
          kucunAward:kucunAward,
          idAward: idAward,

        })


        that.setAward();

      
      }
    });
  },


  //获取卡券列表
  getcardlist:function(){
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "getcardlist",
        "uid": that.data.uid
      },
      
      success: function (responseData) {
        console.log("卡券数据：", responseData.data.get);

        var cardlist = responseData.data.get;
        var imageAward = [];
        var nameAward = [];
        var kucunAward = [];
        for(var i = 0; i<cardlist.length; i++){
          imageAward[i] = cardlist[i].image;
          nameAward[i] = cardlist[i].title;
          kucunAward[i] = "10";
        }
        console.log("商店商品图片:", imageAward);
        console.log("商店商品名字:", nameAward);
        console.log("商店商品库存:", kucunAward);
        that.setData({
          cardlist:cardlist,
          imageAward: imageAward,
          nameAward:nameAward,
          kucunAward:kucunAward,

        })


        that.setAward();

      }
    });
  },


  setAward:function (){
    var that = this;
    //圆点设置  
    var leftCircle = 7.5;  
    var topCircle = 7.5;  
    var circleList = [];  
    for (var i = 0; i < 24; i++) {  
      if (i == 0) {  
        topCircle = 15;  
        leftCircle = 15;  
      } else if (i < 6) {  
        topCircle = 7.5;  
        leftCircle = leftCircle + 102.5;  
      } else if (i == 6) {  
        topCircle = 15  
        leftCircle = 620;  
      } else if (i < 12) {  
        topCircle = topCircle + 94;  
        leftCircle = 620;  
      } else if (i == 12) {  
        topCircle = 565;  
        leftCircle = 620;  
      } else if (i < 18) {  
        topCircle = 570;  
        leftCircle = leftCircle - 102.5;  
      } else if (i == 18) {  
        topCircle = 565;  
        leftCircle = 15;  
      } else if (i < 24) {  
        topCircle = topCircle - 94;  
        leftCircle = 7.5;  
      } else {  
        return 
      }  
      circleList.push({ topCircle: topCircle, leftCircle: leftCircle });  
    }  
    this.setData({  
      circleList: circleList  
    })  
   
    //圆点闪烁  
    setInterval(function () {  
      if (that.data.colorCircleFirst == '#FFDF2F') {  
        that.setData({  
          colorCircleFirst: '#FE4D32',  
          colorCircleSecond: '#FFDF2F',  
        })  
      } else {  
        that.setData({  
          colorCircleFirst: '#FFDF2F',  
          colorCircleSecond: '#FE4D32',  
        })  
      }  
    }, 1000)//设置圆点闪烁的效果  
   
    //奖品item设置  
    var awardList = [];  
    //间距,怎么顺眼怎么设置吧.  
    var topAward = 25;  
    var leftAward = 25;  
    for (var j = 0; j < 8; j++) {  
      if (j == 0) {  
        topAward = 25;  
        leftAward = 25;  
      } else if (j < 3) {  
        topAward = topAward;  
        //166.6666是宽.15是间距.下同  
        leftAward = leftAward + 166.6666 + 15;  
      } else if (j < 5) {  
        leftAward = leftAward;  
        //150是高,15是间距,下同  
        topAward = topAward + 150 + 15;  
      } else if (j < 7) {  
        leftAward = leftAward - 166.6666 - 15;  
        topAward = topAward;  
      } else if (j < 8) {  
        leftAward = leftAward;  
        topAward = topAward - 150 - 15;  
      }  
      var imageAward = this.data.imageAward[j]; 
      var idAward = this.data.idAward[j];
      console.log("imageAward:"+imageAward); 
      awardList.push({ topAward: topAward, leftAward: leftAward, imageAward: imageAward, idAward: idAward });  
    }  
    this.setData({  
      awardList: awardList  
    })  
  },
   
  //开始抽奖  
  startGame: function () {  
    var that = this;
    var item = true;
    var kucun = that.data.kucunAward;
    for(var j = 0; j<kucun.length; j++){
      if(kucun[j] != 0){
        item = false;
      }
    }

    if(item){
      var contentkucun = that.data.tc == 1 ? '庫存不足,敬請期待' : '库存不足,敬请期待';
      wx.showModal({  
          title: '提示',  
          content: contentkucun, 
          confirmText: that.data.tc == 1 ? '確認' : '确认', 
          showCancel: false,//去掉取消按钮   
      });
      return 
    }


    if (that.data.isRunning) return 
    console.log("user_jifen"+that.data.user_jifen);
    if(that.data.inviteCount < 0 ){
      that.getData(); //这里大于0会不扣积分直接抽奖
    }else{
      if(that.data.user_jifen < that.data.gameIntegral){
        var contentname = that.data.tc == 1 ? '積分不足'+that.data.gameIntegral+'分' : '积分不足'+that.data.gameIntegral+'分';
        wx.showModal({  
            title: '提示',  
            content: contentname,  
            showCancel: false,//去掉取消按钮   
        });
        return;
      }else{
        var privatekey = utilMd5.hexMD5(that.data.uid + 'consumesource' + that.data.token);
        
        util.api({
          method: "post",
          data: {
            "uid": that.data.uid,
            "source": that.data.gameIntegral,
            "ac": "consumesource",
            privatekey : privatekey
          },
          
          success: function (responseData) {
            console.log("调试--扣积分接口:", responseData.data);
            if(responseData.data.msg == "success"){
              that.getJifen();
              that.getData();
            }else{
              var contentname = that.data.tc == 1 ? '抽獎失敗,請聯系管理員' : '抽奖失败,请联系管理员';
              wx.showModal({  
                  title: '提示',  
                  content: contentname,  
                  showCancel: false,//去掉取消按钮   
              });
              return ;
            }
            
          }
        });
      }
    }
    

    
   
  },

  //抽奖流程
  getData:function(){
    var that = this;
     this.setData({  
      isRunning: true 
    })  
    var indexSelect = 0  
    var i = 0;  
    

    var timer = setInterval(function () {
      indexSelect++;
 
      if(that.data.kucunAward[indexSelect-1] != 0){ 
        //这里我只是简单粗暴用y=30*x+200函数做的处理.可根据自己的需求改变转盘速度 

        i += Math.random()*300; 
  
        if (i > 1000) {  
          //去除循环  
          clearInterval(timer)  
          //获奖提示  
          var key = that.data.indexSelect;
          var nameData = that.data.nameAward;
          var idData = that.data.idAward;
          var name =  nameData[key];
          
          console.log("key"+key+"nameData"+name);

          if(name == undefined){
            wx.showModal({  
              title: '',  
              content: '谢谢参与',  
              showCancel: false,//去掉取消按钮  
            })  
            that.setData({  
              isRunning: false 
            }); 
          }else{
            wx.showModal({  
              title: '恭喜您',  
              content: '获得了' + name + "一份",  
              showCancel: false,//去掉取消按钮  
              success: function (res) {  
                if (res.confirm) { 

                  that.setData({  
                    isRunning: false 
                  }); 
                  // that.setPrize();

                  that.newQuan();
                }  
              }  
            })  
          }
          
        }  
      }
      
      indexSelect = indexSelect % 8;  
      that.setData({  
        indexSelect: indexSelect  
      })  
    }, (200 + i))  
  },


  //添加奖品到购物车
  setPrize:function(){
    var that = this;
    var key = that.data.indexSelect-1;
    var resData = that.data.resData;
    var newData=that.data.goodsList.concat(resData);
    var good = [];
    for(var j = 0;j<newData.length;j++){
        good = newData[key];
        
    }
    

     var gwc_datas = wx.getStorageSync('draw_datas');
      if (!gwc_datas) {
        gwc_datas = [];
      }

      var goodsInfo = {};
      goodsInfo.id = good.id;
      goodsInfo.ghsid = good.postuid;
      goodsInfo.title = good.topictitle;
      goodsInfo.def_img = good.photoscbk[0].photo;
      goodsInfo.sel = true;
      goodsInfo.guigeName = good.guige ? good.guige : '';
      goodsInfo.selGuige = this.data.selectGuige;
      if (good.pin == 1) {//拼单商品
        goodsInfo.price = good.pinprice;
      } else {
        goodsInfo.price = this.data.selectGuige ? this.data.selectGuige.price : good.sellprice;
      }
      goodsInfo.yunfei = good.yunfei;
      goodsInfo.kucun = good.kucun;
      goodsInfo.buycount = this.data.countValue;
      goodsInfo.source = good.source;
      goodsInfo.pin = good.pin;//这里加是否是拼单商品标记
      goodsInfo.pinzong = good.pinzong;//这个是拼单的 期数，通常一天为一个拼单周期
      goodsInfo.linkcode = good.linkcode;//商品唯一32位id
      
      var addItem = [goodsInfo];
      var hasSameGoods = false;

      //获取规格商品
      that.getGuigeData(good.id);

      if(gwc_datas.length > 0){
        for(var i = gwc_datas.length - 1; i >= 0; i--){
          if(gwc_datas[i].id == goodsInfo.id){
            if(this.data.guigeData.length > 0){
              if (gwc_datas[i].selGuige.id == goodsInfo.selGuige.id){
                hasSameGoods = true;
                gwc_datas[i].buycount = gwc_datas[i].buycount + goodsInfo.buycount;
              }
            } else {
              hasSameGoods = true;
              gwc_datas[i].buycount = gwc_datas[i].buycount + goodsInfo.buycount;
            }
          }
        }
      }
      if(!hasSameGoods){
        gwc_datas = addItem.concat(gwc_datas);
        var count = this.data.gwc_count + 1;
        this.setData({
          gwc_count: count
        })
      }
      console.log("gwc_datas====:"+gwc_datas);
       console.log("gwc_datas====:"+gwc_datas.length);
      wx.setStorageSync('draw_datas', gwc_datas); 
      var newInputValue = this.data.countValue + 1;
      this.setData({
        countValue: newInputValue
      })
      
      that.buyAction();
  },

  getGuigeData: function (g_id) {
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "goodsguige",
        "goods_id": g_id
      },
      success: function (responseData) {
        console.log("商品规格：", responseData.data)
        if (!responseData.data.msg) {
          var selGuige = responseData.data[0];
          that.setData({
            guigeData: responseData.data,
            selectGuige: selGuige
          })
        }
      }
    });
  },

  //跳转确认订单页面
  buyAction:function(){
    var allData = wx.getStorageSync('draw_datas');
    console.log("allData:===="+allData);
    var jiesuanArr = [];
    for (var i = 0; i < allData.length; i++) {
      if (allData[i].sel) {
        jiesuanArr = jiesuanArr.concat(allData[i]);
        }
      }
      this.setData({
       goodsinfoArr: jiesuanArr,
      })
      // var jieSuanStr = JSON.stringify(jiesuanArr);
      // var url = "/pages/order-confirm/order-confirm?goodsArr=" + jieSuanStr + "&payType=2";
      // var url = "/pages/myrecord/myrecord";
      // wx.navigateTo({ url: url });
      this.paygoodsCard();
  },


  paygoodsCard: function () {
    if (wxAuthFail) {
      app.reAuthorize(this.reGetUserInfo);
      return;
    }
    var that = this;
    var privatekey = utilMd5.hexMD5(that.data.uid + 'setprize' + that.data.token);


    // that.saveAddress();
    var cartinfoArr = [];
    var pin = 0;
    for (var i = 0; i < this.data.goodsinfoArr.length; i++){
      var goodsItem = this.data.goodsinfoArr[i];
      var g_info = {};
      g_info.goods_id = goodsItem.id;
      g_info.goods_name = goodsItem.title;
      g_info.guige = goodsItem.selGuige ? goodsItem.selGuige.id : '';
      g_info.count = goodsItem.buycount;
      g_info.yunfei = goodsItem.yunfei;
      g_info.coin = goodsItem.price * goodsItem.buycount + g_info.yunfei * 100;
      g_info.linkcode = goodsItem.linkcode;
      cartinfoArr = cartinfoArr.concat(g_info);
      pin = (goodsItem.pin == 1 ? goodsItem.pinzong : 0);
    }
    var data = {
      'cartinfo': JSON.stringify(cartinfoArr),

      'uid': that.data.uid,
      'type': 'goods',
      'total_fee': 0.01,
      'allcoin': 1,
      'consignee': '',
      'phone': '',
      'addr': '',
      'psd_phone': '',
      'subject': '购买商品-批量结算' ,
      'openid': that.data.openid,
      'publickey': util.publiccode,
      'ac': "setprize",
      'privatekey': privatekey,
      'del_source': 0,
      'add_source': 0,
      'message': '',
      'pin': 0,
      'ziti': 1,
      'isdraw': 1,
      'debug':1
    };
    console.log("购物车订单参数：", data);
    // return;
    //下单请求
    util.api({
      data: data,
      method: 'POST',
      success: function (responseData) {
            that.clearGouwuche();
            
            var url = "/pages/myrecord/myrecord";
            wx.navigateTo({ url: url });
       
      }
    });
  }, 


  //清除购物车缓存
  clearGouwuche:function(){
    var gwc_datas  = wx.getStorageSync('draw_datas');
    if (gwc_datas && gwc_datas.length > 0) {
      var new_gwc_datas = [];
      for (var i = 0; i < gwc_datas.length; i++) {
        var g_id = gwc_datas[i].id;
        var guige_id = gwc_datas[i].selGuige ? gwc_datas[i].selGuige.id : '';
        var notPay = true;
        for (var n = this.data.goodsinfoArr.length - 1; n >= 0; n--) {
          var pay_g_id = this.data.goodsinfoArr[n].id;
          var pay_guige_id = this.data.goodsinfoArr[n].selGuige ? this.data.goodsinfoArr[n].selGuige.id : '';
          if (g_id == pay_g_id && guige_id == pay_guige_id) {
            notPay = false;
            break;
          }
        }
        if (notPay) {
          new_gwc_datas = new_gwc_datas.concat(gwc_datas[i]);
        }
      }
      if (new_gwc_datas.length > 0) {
     
          wx.setStorageSync('draw_datas', new_gwc_datas);
        
        
      } else {
        
          wx.removeStorageSync("draw_datas");
        
        
      }
    }
  }, 



  //我的记录
  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({ url: url })
  },

  //页面分享
  onShareAppMessage: function () {
    var that = this;
    var inviteuid = that.data.uid ? that.data.uid : '';
    console.log("inviteuid:" + inviteuid);
    return {
      title: 'MBM车臣仕助力抽奖，百分百中奖！！！',
      path: '/pages/draw/draw?&inviteuid=' + inviteuid
    };
  },

  //获取积分
  getJifen: function () {
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "getusersource",
        "uid": that.data.uid
      },
      
      success: function (responseData) {
        console.log("积分:"+responseData.data.source);
        that.setData({
          user_jifen: responseData.data.source
        })
      }
    });
  },


  //请求邀请总人数
  loadInviteCount: function () {
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "invitecount",
        "uid": that.data.uid
      },
      success: function (responseData) {
        console.log("邀请人数"+responseData.data.count);
        that.setData({
          inviteCount: responseData.data.count ? responseData.data.count : 0
        });
      }
    });
  },



  newQuan: function () {
    var that = this;
    var key = that.data.indexSelect-1;
    var cardlist = that.data.cardlist;
   
  
console.log("cardlist==="+cardlist);
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "getcard",
        "id": util.appid,
        "uid": that.data.uid,
        "cardId": cardlist[key].cardId,
        //"cardId":"pD0RuwobZX56cuxKq90kSJXZVKLI",

      },
      success: function (responseData) {
        console.log("getcard==="+responseData);
        var signdata = responseData.data;
        console.log("signdata==="+signdata);
        var cext = '{"openid":"' + signdata.openid + '","nonce_str":"' + signdata.nonce_str + '","timestamp":"' + signdata.timestamp + '","signature":"' + signdata.signature + '"}';
        console.log(cext)
        wx.addCard({
          cardList: [{
            cardId: signdata.cardId,
            cardExt: '{"openid":"' + signdata.openid + '","nonce_str":"' + signdata.nonce_str + '","timestamp":"' + signdata.timestamp + '","signature":"' + signdata.signature + '"}'
          }], // 需要添加的卡券列表
          success: function (res) {
            console.log(res);
            var addinfo = res['cardList'][0]
            //抽奖记录保存
                util.api({
                  method: "post",
                  data: {
                    "publickey": util.publiccode,
                    "ac": "saveuserrecord", 
                    "appid": util.appid,
                    "uid": that.data.uid,
                    "cardId": addinfo.cardId,
                    "privatekey": utilMd5.hexMD5(that.data.uid + 'saveuserrecord' + that.data.token)

                  },
                  success: function (responseData) {
                    console.log("抽奖记录保存:",responseData)
                    
                  }
                });

            util.api({
              method: "post",
              data: {
                "publickey": util.publiccode,
                "ac": "saveusercard", 
                "appid": util.appid,
                "uid": that.data.uid,
                "cardId": addinfo.cardId,
                "code": addinfo.code,
                "cartExt": addinfo.cartExt,
                "isSuccess": addinfo.isSuccess,
                "privatekey": utilMd5.hexMD5(that.data.uid + 'saveusercard' + that.data.token)

              },
              success: function (responseData) {
                console.log(responseData);
                
              }
            });
            console.log("你成功领取了奖品！");
          },
          cancel: function (res) {
            console.log(res)
            console.log('已取消')
          },
          fail: function (res) {
            console.log(res)
            console.log("失败")

          }
        });
      }
    });
  },
  resetNavColor: function () {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },

})
